//
//  SFNetworkManager.swift
//  SFWeiboPro
//
//  Created by happy on 2017/9/9.
//  Copyright © 2017年 happy. All rights reserved.
//

import UIKit
import AFNetworking

enum SFHTTPMethod {
    case GET
    case POST
}

class SFNetworkManager: AFHTTPSessionManager {
    
    static let shareManager = SFNetworkManager()
    
//    var accessToken: String? //= "2.00GkH66GCz3lwD43cf3ee1830f2oHs"
    
    lazy var userAccount = SFUserAcount()
    
    ///用户登录标记
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    //利用token来发请求
    func tokenRequest(method: SFHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion:@escaping (_ json: AnyObject?,_ isSuccess: Bool) -> ()) {
        
        //判断token是否存在
        guard let token = userAccount.access_token else {
            print("没有token")
            completion(nil, false)
            
            // FIXME: 发送通知
            return
        }
        
        //获取字典参数
        var parameters = parameters
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = token as AnyObject
        
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    
    func request(method: SFHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion:@escaping (_ json: AnyObject?,_ isSuccess: Bool) -> ()) {
        
        let sfSuccess = {(task: URLSessionDataTask, json: Any?)->(Void) in
            completion(json as AnyObject, true)
        }
        
        let sfFailure = {(task:URLSessionDataTask?, error: Error)->() in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                //FIXME: 发送通知,token已过期
            }
            print("网络请求失败: \(error)")
            
            completion(nil, false)
        }
        
        if method == .GET {
            
            get(URLString, parameters: parameters, progress: nil, success: sfSuccess, failure: sfFailure)
            
        }
        else
        {
           post(URLString, parameters: parameters, progress: nil, success: sfSuccess, failure: sfFailure)
        }
        
    }
//    private override init() {
//        
//    }
    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }

}
